package cn.superchart.common.utils;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.superchart.common.base.BaseJwtUser;
import cn.superchart.common.properties.SecurityProperties;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
@Slf4j
public class JwtUtils {

    private final static SecurityProperties securityProperties = SpringUtil.getBean(SecurityProperties.class);

    private static final String SECRET_KEY = securityProperties.getJwt().getSecretKey();

    private static final String ISSUER = "SuperChart";

    private static final String SUBJECT = "SuperChartUsers";

    private static final String USER_ID = "userId";

    private static final String ACCOUNT = "account";

    private static final Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);

    public static String createToken(Long expired,String userId,String account){
            JWTCreator.Builder build = JWT.create()
            // JWT发行者
            .withIssuer(ISSUER)
            // 主题
            .withSubject(SUBJECT)
            // 用户名 account 信息
            .withClaim(ACCOUNT, account)
            // 用户名ID信息
            .withClaim(USER_ID, userId);
            if(Checker.BeNotNull(expired)){
                // 设置过期时间
                 Date expiredDate =  DateUtil.offsetSecond(new DateTime(),expired.intValue());
                 build.withExpiresAt(expiredDate);
            }
            return build.sign(algorithm);
    }

    public static BaseJwtUser getUser(String token){
        if(Checker.BeNotBlank(token)){
            try {
                DecodedJWT decodedJWT = JWT.require(algorithm).withIssuer(ISSUER).build().verify(token);
                BaseJwtUser baseJwtUser = new BaseJwtUser();
                baseJwtUser.setUserId( decodedJWT.getClaim(USER_ID).asString());
                baseJwtUser.setAccount( decodedJWT.getClaim(ACCOUNT).asString());
                return baseJwtUser;
            }catch (Exception e){
               log.error("Invalid or expired JWT");
            }
        }
        return null;
    }


//    public static void main(String[] args) {
//        // 密钥（建议使用更复杂的密钥）
//        String secretKey = "your_secret_key";
//
//        // 设置JWT的有效期（例如，30分钟）
//        long expireMillis = 1 * 60 * 1000;  // 30分钟的毫秒数
//        long currentTimeMillis = System.currentTimeMillis();
//        Date expireDate = new Date(currentTimeMillis + expireMillis);  // 设置过期时间
//
//        // 创建JWT的签名算法
//        Algorithm algorithm = Algorithm.HMAC256(secretKey);
//
//        // 创建JWT并设置payload数据和过期时间
//               String token = JWT.create().
//                withIssuer("your_issuer") // JWT发行者
//                .withIssuer("your_issuer")
//                .withSubject("user123")     // 主题
//                .withClaim("username", "testUser")  // 用户名信息
//                .withClaim("userId", 123)   // 用户ID信息
//                .withExpiresAt(expireDate)  // 设置过期时间
//                .sign(algorithm);           // 签名JWT
//
//        // 打印生成的JWT
//        System.out.println("Generated JWT: " + token);
//
//        // 验证JWT并解密
//        try {
//            DecodedJWT decodedJWT = JWT.require(algorithm)
//                    .withIssuer("your_issuer")  // 必须与生成时一致
//                    .build()
//                    .verify("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ5b3VyX2lzc3VlciIsInN1YiI6InVzZXIxMjMiLCJ1c2VybmFtZSI6InRlc3RVc2VyIiwidXNlcklkIjoxMjMsImV4cCI6MTczMjAwNzE0NH0.RH-fslRbyX3U5EhirIBFz-eG24GJLcnqepaLDDGxZZU");  // 验证Token是否有效
//
//            // 打印JWT信息
//            System.out.println("Decoded JWT: " + decodedJWT.getToken());
//            System.out.println("Username: " + decodedJWT.getClaim("username").asString());
//            System.out.println("User ID: " + decodedJWT.getClaim("userId").asInt());
//        } catch (Exception e) {
//            System.out.println("Invalid or expired JWT");
//        }
//    }
}
